﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mail;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using PhotoGalleryEnteties;
using PhotogalleryModel;
using photogalleryMVC.Models;

namespace photogalleryMVC.Controllers
{

    
    public class AccountController : PhotoGalleryController 
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

       


        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

           
            

            base.Initialize(requestContext);
        }

 
        public ActionResult UserMenu()
        {
            if(User.Identity.IsAuthenticated )
            {
                ViewData["UserName"] = User.Identity.Name;
                GalleryUser user = UserRepository.GetUserByName(User.Identity.Name);
               
                ViewData["NewsCount"] = NewsRepository.NewsCount(user);
                
                 ViewData["RootId"] = user.RootAlbum.AlbumId ;
                return View("AuthUserMenu");
            }
            return View("LogOnPartial");
        }

        [Authorize]
        public JsonResult GetNewsCount()
        {
            GalleryUser user = UserRepository.GetUserByName(User.Identity.Name);
            return Json(NewsRepository.NewsCount(user));
        }


        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }


        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            
            if (ModelState.IsValid && MembershipService.ValidateUser(model.UserName, model.Password))
            {
                    
                FormsService.SignIn(model.UserName, model.RememberMe);
                   
            }
            else
            {
                TempData["LogOnMessage"] = "Specified login and pass combination doesn`t exist";
            }
            if (!String.IsNullOrEmpty(returnUrl))
             {
                 return Redirect(returnUrl);
             }
             else
             {
                 return RedirectToAction("Index", "Home");
             }
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff(string returnUrl)
        {
            FormsService.SignOut();
            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            return RedirectToAction("Index", "Home");

        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email,model.PasswordQuestion ,model.PasswordAnswer );

                if (createStatus == MembershipCreateStatus.Success)
                {
                    //Create infrastructure for user 
                    GalleryUser user = UserRepository .GetUserByName(model.UserName);
                    user.RoleName = GalleryUserRepository .DefaultUserRole;
                    Album root = AlbumRepository .CreateAlbum();
                    root.Title = AlbumRepository.CreateRootName(user.UserName);
                    root.Owner = user;
                    user.RootAlbum = root;
                    ModelContext .SaveChanges();
                   

                    
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        
        //Get: /account/SetAvatar/5?returnurl=someurl
        [Authorize ]
        public ActionResult  SetAvatar(int id ,string returnUrl)
        {
            PhotoInfo avatar = PhotoRepository.GetPhotoInfo(id);
            if(avatar==null)
            {
                TempData.Add("Messages", string.Format("Photo with Id {0} doesn`t exist", id));
            }
            else
            {
                GalleryUser user = UserRepository.GetUserByName(avatar.Album.Owner.UserName);
                if(string.Compare(  User.Identity .Name,user.UserName  ,true   )!=0)
                    TempData.Add("Messages", new string[] { "You can set as avatars only your own photos " });
                else
                {
                    user.Avatar = avatar;
                    ModelContext .SaveChanges();
                }
            }

            if (returnUrl != null)
                return Redirect(returnUrl);
            else
                return RedirectToAction("Index", "Home");
        }


       

        public JsonResult CheckName(string userName)
        {
            if (UserRepository.UsenameExists(userName))
                return Json("specified name exists", JsonRequestBehavior.AllowGet);
            return Json(true, JsonRequestBehavior.AllowGet);

        }

        public JsonResult CheckEmail(string email)
        {
            if (UserRepository.CheckEmail( email))
                return Json("specified email exists", JsonRequestBehavior.AllowGet);
            return Json(true, JsonRequestBehavior.AllowGet);
        }


        public ActionResult GetQuestion()
        {
            return View();
        }

        [HttpPost ]
        public ActionResult GetQuestion( GetQuestionModel model)
        {
            try
            {
                AnswerModel answer = new AnswerModel()
                                         {
                                             Question = MembershipService.GetQuestion(model.MailOrName),
                                             Mail = MembershipService .GetEmail(model.MailOrName )
                                         };
                if(ModelState.IsValid )
                    return View("AnswerQuestion", answer);
            }
            catch(ArgumentException ex)
            {
                ModelState.AddModelError("", "Specified user does not exist");
            }
            return View(model );
        }

        [HttpPost ]
        public ActionResult AnswerQuestion(AnswerModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    string newPassword = MembershipService.ResetPass(model.Mail, model.Answer);
                    MembershipService.SendNewPassword(newPassword, model.Mail);
                    return View("RestoreSuccess");
                }
            }
            catch(MembershipPasswordException mem)
            {
                ModelState.AddModelError("", mem.Message);
            }
            return View(model);
        }


        public ActionResult About()
        {
            return View();
        }




    }
}
